import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { In, Not, Repository } from 'typeorm';
import { AgentRelationEntity } from '../entity/agentRelation';
import { BaseSysUserEntity } from '../../base/entity/sys/user';
import { OrderShopEntity } from '../../order/entity/shop';
import { BaseSysUserRoleEntity } from '../../base/entity/sys/user_role';
import { OrderOrderEntity } from '../../order/entity/order';
import { OrderCityEntity } from '../../order/entity/city';
import { UserInfoEntity } from '../../user/entity/info';

interface AgentRelationDict {
  id: string;
  agentType: string;
  agentLevel: number;
  type: string;
  thisUserAgentLevel: number; // 当前登录用户的代理层级
  children: Array<{
    id: number;
    agentType: string;
    agentName: string;
    agentLevel: number;
    agentShopName: string;
    agentShopIds: number[];
    agentUserId: number;
    parentAgentUser: string; // 上级代理商
    type: string;
  }>;
}

interface AgentBoardDict {
  cityId: number; // 城市id
  cityName: string; // 城市名称
  orderCount: number; // 订单数量
  amount: number; // 订单金额
  agentArr: Array<{
    amount: number; // 订单金额
    agentName: string; // 代理商名称
    // agentLevel: number; // 代理商等级
    agentUserId: number; // 代理商用户id
    shopArr: Array<{
      shopId: number; // 店铺id
      shopName: string; // 店铺名称
      orderCount: number; // 订单数量
      amount: number; // 订单金额
    }>;
  }>;
}

/**
 * 代理关系服务
 */
@Provide()
export class AgentRelationService extends BaseService {
  @InjectEntityModel(AgentRelationEntity)
  agentRelationEntity: Repository<AgentRelationEntity>;
  @InjectEntityModel(BaseSysUserEntity)
  baseSysUserEntity: Repository<BaseSysUserEntity>;
  @InjectEntityModel(BaseSysUserRoleEntity)
  baseSysUserRoleEntity: Repository<BaseSysUserRoleEntity>;
  @InjectEntityModel(OrderShopEntity)
  orderShopEntity: Repository<OrderShopEntity>;
  @InjectEntityModel(OrderOrderEntity)
  orderOrderEntity: Repository<OrderOrderEntity>;
  @InjectEntityModel(OrderCityEntity)
  orderCityEntity: Repository<OrderCityEntity>;

  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  async selectAgentRelationDict(userRes: BaseSysUserEntity) {
    return this.agentRelationEntity.findOne({
      where: {
        agentShopIds: In([userRes.shopId]),
      },
    });
  }

  @Inject()
  ctx;

  // 获取店铺对应的二级代理商和一级代理商
  async orderShopAgentMap() {
    const shops = await this.orderShopEntity.find();
    if (!shops) {
      throw new Error('店铺不存在');
    }
    const relations = await this.agentRelationEntity.find();
    const agents = await this.baseSysUserEntity.find();
    const returnArray = [];
    shops.map(shop => {
      const relation = relations.find(item => item.agentShopIds.ids.includes(shop.id));
      if (relation) {
        const agent = agents.find(item => item.id === relation.agentUserId);
        if (agent) {
          const item = {
            ...shop,
            agentUserId: agent.id,
            agentName: agent.name,
          }
          returnArray.push(item);
        }
      }
    })
    
    return returnArray;
  }

  // 根据agentId递归获取下面的节点，并且排除已查询出来的id
  async getChildrenAgentIds(agentId: number, excludeIds: number[] = []) {
    // 排除已查询出来的id
    excludeIds.push(agentId);
    const children = await this.agentRelationEntity.find({
      where: {
        parentAgentId: agentId,
      },
    });
    const childIds = children.map(item => item.agentUserId);
    // 递归获取所有子节点的ID
    for (const child of children) {
      childIds.push(...await this.getChildrenAgentIds(child.agentUserId, excludeIds));
    }
    return childIds;
  }

  // 根据递归获取到的agentUserId查询所有的agentShopIds
  async getAgentShopIds(agentIds: number[]) {
    const res = await this.agentRelationEntity.find({
      where: {
        agentUserId: In(agentIds),
      },
    });
    const shopIds = res.map(item => item.agentShopIds.ids).flat();
    return shopIds;
  }

  // 将getChildrenAgentIds和getAgentShopIds合并为一个方法
  async getAgentShopIdsByAgentId(agentId: number) {
    const childIds = await this.getChildrenAgentIds(agentId);
    // 需要拼上自己的
    childIds.push(agentId);
    const shopIds = await this.getAgentShopIds(childIds);
    return shopIds;
  }

  // 获取一级代理商数组，联查出姓名
  async getLevelAgents(level = 1) {
    const res = await this.agentRelationEntity.find({
      where: {
        level,
      },
    });
    // 联查出姓名
    const agentIds = res.map(item => item.agentUserId);
    const agents = await this.baseSysUserEntity.find({
      where: {
        id: In(agentIds),
      },
    });
    // 构建映射表
    const agentMap = new Map(agents.map(agent => [agent.id, agent]));
    
    return res.map(item => ({
        label: agentMap.get(item.agentUserId)?.name || '-',
        value: item.agentUserId
    }));
  }

  // 根据一级代理商查出二级代理商
  async getSecondLevelAgents(firstAgentId: number) {
    const res = await this.agentRelationEntity.find({
      where: {
        parentAgentId: firstAgentId,
      },
    });
    // 联查出姓名
    const agentIds = res.map(item => item.agentUserId);
    const agents = await this.baseSysUserEntity.find({
      where: {
        id: In(agentIds),
      },
    });
    // 构建映射表
    const agentMap = new Map(agents.map(agent => [agent.id, agent]));
    
    return res.map(item => ({
        label: agentMap.get(item.agentUserId)?.name || '-',
        value: item.agentUserId
    }));
  }

  // 查询代理商信息
  async queryAgentById(body: { agentUserId: number }) {
    console.log(body);
    const res = await this.baseSysUserEntity.findOne({
      where: {
        id: body.agentUserId,
      },
    });
    return res;
  }

  // 查询代理商铺
  async queryAgentShopById(body: { ShopIds: number[] }) {
    console.log(body);
    if (body.ShopIds && body.ShopIds.length > 0) {
      const shop = await this.orderShopEntity.find({
        where: {
          id: In(body.ShopIds),
        },
      });
      return shop;
    }
    return {};
  }

  // 计算代理关系
  async processAgent(agent, agentType) {
    let resList = [];
    // 先收集所有需要查询的shopId
    const allShopIds = [];
    agent.forEach(item => {
      if (item.agentShopIds && item.agentShopIds.ids) {
        allShopIds.push(...item.agentShopIds.ids);
      }
    });

    // 一次性查询所有店铺信息，避免多次数据库操作
    const shopsMap = new Map();
    if (allShopIds.length > 0) {
      const shops = await this.orderShopEntity.find({
        where: {
          id: In(allShopIds),
        },
      });
      // 构建店铺ID到名称的映射
      shops.forEach(shop => {
        shopsMap.set(shop.id, shop.name);
      });
    }
    let tempAgentDict = {
      id: null,
      agentUserId: null,
      agentType: agentType,
      agentName: null,
      agentLevel: null,
      agentShopName: '',
      agentShopIds: [],
      parentAgentId: null,
      parentAgentUser: '', // 上级代理商
      type: 'node',
    };

    // 处理每个代理关系，设置店铺名称
    for (const item of agent) {
      // 获取上级代理商用户名
      const parentAgentUser = item.parentAgentId
        ? await this.getParentAgentUserName(item.parentAgentId)
        : '';

      tempAgentDict = {
        id: item.agent_id,
        agentUserId: item.agentUserId,
        agentType: agentType,
        agentName: item.user_name,
        agentLevel: item.agent_level,
        agentShopName: '',
        parentAgentId: item.parentAgentId,
        parentAgentUser: parentAgentUser,
        agentShopIds: item.agentShopIds?.ids || [],
        type: 'node',
      };

      // 从映射中获取并拼接店铺名称
      if (item.agentShopIds && item.agentShopIds.ids) {
        const shopNames = item.agentShopIds.ids
          .map(id => shopsMap.get(id) || '')
          .filter(name => name); // 过滤空名称
        tempAgentDict.agentShopName = shopNames.join(',');
      }
      resList.push(tempAgentDict);
    }
    return resList;
  }

  // 获取上级代理商名称
  async getParentAgentUserName(parentAgentId: number): Promise<string> {
    try {
      const parentUser = await this.baseSysUserEntity.findOne({
        where: {
          id: parentAgentId,
        },
      });
      return parentUser?.name || '';
    } catch (error) {
      console.error('获取父代理用户名失败:', error);
      return '';
    }
  }

  // 递归获取指定层级的所有下级代理
  private async findAllSubAgentsByLevel(
    parentAgentIds: number[],
    level: number
  ): Promise<any[]> {
    // 递归终止条件：如果没有父代理ID，则返回空数组
    if (!parentAgentIds || parentAgentIds.length === 0) {
      return [];
    }

    // 查询直接下级代理
    const directAgents = await this.agentRelationEntity
      .createQueryBuilder('agent')
      .leftJoinAndMapOne(
        'agent.agentUserId',
        BaseSysUserEntity,
        'user',
        'agent.agentUserId = user.id'
      )
      .where('agent.parentAgentId IN (:...parentAgentIds)', {
        parentAgentIds,
      })
      .select([
        'agent.id',
        'agentUserId',
        'agentShopIds',
        'agent.level',
        'agent.parentAgentId as parentAgentId',
        'user.name',
      ])
      .getRawMany();

    // 如果是最低级别或没有下级代理，则直接返回
    if (level <= 1 || directAgents.length === 0) {
      return directAgents;
    }

    // 递归查询下一级代理
    const agentUserIds = directAgents.map(agent => agent.agentUserId);
    const subAgents = await this.findAllSubAgentsByLevel(
      agentUserIds,
      level - 1
    );

    // 合并直接下级和间接下级代理
    return [...directAgents, ...subAgents];
  }

  // 获取代理级别对应的中文名称
  private getAgentLevelName(level: number): string {
    if (level === 1) return '一级代理';
    if (level === 2) return '二级代理';
    if (level === 3) return '三级代理';
    if (level === 4) return '四级代理';
    return `${level}级代理`;
  }

  // 查询代理关系
  async queryAgentRelation(body: {}) {
    // 用户信息
    const userRes = await this.baseSysUserEntity.findOne({
      where: {
        id: this.ctx.admin.userId,
      },
    });

    // 获取用户的代理信息
    const userLevel = await this.agentRelationEntity.findOne({
      where: {
        agentUserId: userRes.id,
      },
    });

    const userLevelNum = userLevel?.level || 0;

    // 查找所有可能的代理层级
    const allLevels = await this.agentRelationEntity
      .createQueryBuilder('agent')
      .select('DISTINCT agent.level as level')
      .getRawMany();

    // 计算最大代理层级
    const maxLevel = Math.max(
      ...allLevels.map(item => parseInt(item.level) || 0),
      2 // 至少支持到二级代理
    );

    const agentListRes: AgentRelationDict[] = [];

    // 动态构建每个层级的代理数据
    for (let currentLevel = 1; currentLevel <= maxLevel; currentLevel++) {
      // 如果当前用户有固定级别，且查询的层级低于用户级别，则跳过
      if (userLevelNum > 0 && currentLevel < userLevelNum) {
        continue;
      }

      let agentsToProcess;

      if (userLevelNum === 0) {
        // 超级管理员或非代理用户，查询所有指定层级的代理
        agentsToProcess = await this.agentRelationEntity
          .createQueryBuilder('agent')
          .leftJoinAndMapOne(
            'agent.agentUserId',
            BaseSysUserEntity,
            'user',
            'agent.agentUserId = user.id'
          )
          .where('agent.level = :currentLevel', {
            currentLevel,
          })
          .select([
            'agent.id',
            'agentUserId',
            'agentShopIds',
            'agent.level',
            'agent.parentAgentId as parentAgentId',
            'user.name',
          ])
          .getRawMany();
      } else if (userLevelNum === 1 && currentLevel === 2) {
        // 一级代理查询其直接下属的二级代理
        agentsToProcess = await this.agentRelationEntity
          .createQueryBuilder('agent')
          .leftJoinAndMapOne(
            'agent.agentUserId',
            BaseSysUserEntity,
            'user',
            'agent.agentUserId = user.id'
          )
          .where(
            'agent.parentAgentId = :parentAgentId AND agent.level = :currentLevel',
            {
              parentAgentId: userRes.id,
              currentLevel,
            }
          )
          .select([
            'agent.id',
            'agentUserId',
            'agentShopIds',
            'agent.level',
            'agent.parentAgentId as parentAgentId',
            'user.name',
          ])
          .getRawMany();
      } else {
        // 使用递归方式查询所有下级代理
        const allSubAgents = await this.findAllSubAgentsByLevel(
          [userRes.id],
          maxLevel
        );
        // 过滤出指定层级的代理
        agentsToProcess = allSubAgents.filter(
          agent => agent.agent_level === currentLevel
        );
      }

      // 如果当前层级没有代理数据，跳过
      if (agentsToProcess.length === 0) {
        continue;
      }

      // 构建当前层级的代理字典
      const agentLevelDict: AgentRelationDict = {
        id: `root_${currentLevel}`,
        agentType: this.getAgentLevelName(currentLevel),
        agentLevel: currentLevel,
        children: [],
        type: 'root',
        thisUserAgentLevel: userLevelNum,
      };

      // 处理代理数据
      agentLevelDict.children = await this.processAgent(
        agentsToProcess,
        this.getAgentLevelName(currentLevel)
      );

      agentListRes.push(agentLevelDict);
    }

    return agentListRes;
  }

  // 获取代理商列表（新增代理商处使用）
  async getAgentList(body) {
    const userIds = await this.baseSysUserRoleEntity.find({
      where: {
        roleId: 8,
      },
    });
    let list;
    // 获取代理商列表
    // 判断是否上级代理商为null，body.level 为 1 时表明此时为一级代理
    if (body.agentChangeType == 'leaderAgent' && body.level - 1 != 0) {
      // 上级代理：只显示当前代理level - 1的代理
      list = await this.baseSysUserEntity
        .createQueryBuilder('user')
        .select(['user.id', 'user.name'])
        .leftJoinAndSelect(
          AgentRelationEntity,
          'agentRelation',
          'agentRelation.agentUserId = user.id'
        )
        .where('user.id IN (:...userIds)', {
          userIds: userIds.map(e => e.userId),
        })
        // 此处body.level为代理商的层级，只查询上一级代理
        .andWhere('(agentRelation.level = :levelMinusOne)', {
          levelMinusOne: body.level - 1,
        })
        .getMany();
    } else {
      const agentUser = await this.agentRelationEntity.find({});
      // 当前层级代理
      list = await this.baseSysUserEntity
        .createQueryBuilder('user')
        .select(['user.id', 'user.name'])
        .leftJoinAndSelect(
          AgentRelationEntity,
          'agentRelation',
          'agentRelation.agentUserId = user.id'
        )
        .where('user.id IN (:...userIds)', {
          userIds: userIds.map(e => e.userId),
        })
        // 此处body.level为代理商的层级
        .andWhere(
          '(agentRelation.level = :level  OR agentRelation.id IS NULL)',
          {
            level: body.level,
          }
        )
        .getMany();
      // 去除已被选择的代理商 （新增）
      if (agentUser.map(e => e.agentUserId).length > 0) {
        if (body.functionType == 'add' || body.level == 1) {
          // 添加模式：过滤所有已选择的代理商
          list = list.filter(
            item => !agentUser.map(e => e.agentUserId).includes(item.id)
          );
        } else if (body.functionType == 'edit' && body.agentUserId) {
          // 编辑模式：过滤已选择的代理商，但保留当前正在编辑的代理商（即自己）
          list = list.filter(
            item =>
              item.id === body.agentUserId ||
              !agentUser.map(e => e.agentUserId).includes(item.id)
          );
        }
      }

      // list = list.getMany();
    }

    return list.map(user => ({
      id: user.id,
      label: user.name,
      value: user.id,
    }));
  }

  // 编辑代理关系
  async updateAgent(body) {
    // console.log(body);
    // 更新代理商关系
    const agentRelation = await this.agentRelationEntity.findOne({
      where: {
        id: body.id,
      },
    });
    if (!agentRelation) {
      throw new Error('代理商关系不存在');
    }
    if (body.agentlevel != 1) {
      agentRelation.parentAgentId = body.parentId;
    } else {
      const updateRes = await this.agentRelationEntity.update(
        {
          parentAgentId: agentRelation.agentUserId,
        },
        {
          parentAgentId: body.agentUserId,
        }
      );
      // console.log(agentRelation.parentAgentId);
    }
    agentRelation.agentUserId = body.agentUserId;
    if (body.agentShopIds.length == 0 || body.agentShopIds == null) {
      agentRelation.agentShopIds = { ids: [] };
    } else {
      agentRelation.agentShopIds = { ids: body.agentShopIds };
    }
    const res = await this.agentRelationEntity.save(agentRelation);
    return 'res';
  }

  // 添加代理关系
  async addAgent(body) {
    console.log(body);

    // 检查该代理商是否已存在
    const existingAgent = await this.agentRelationEntity.findOne({
      where: {
        agentUserId: body.agentUserId,
      },
    });

    if (existingAgent) {
      // 代理商已存在，返回错误信息
      throw new Error(`代理商用户ID ${body.agentUserId} 已存在，无法重复添加`);
    }

    const agentRelation = new AgentRelationEntity();
    // 判断是否为一级代理，即无上级代理
    if (body.parentAgentId == 0) {
      body.parentAgentId = this.ctx.admin.userId;
    }
    agentRelation.level = body.level;
    agentRelation.agentUserId = body.agentUserId;
    if (body.agentShopIds.length == 0) {
      agentRelation.agentShopIds = { ids: [] };
    } else {
      agentRelation.agentShopIds = { ids: body.agentShopIds };
    }
    agentRelation.parentAgentId = body.parentAgentId;
    const res = await this.agentRelationEntity.save(agentRelation);
    return res;
  }

  // 获取代理商订单（使用动态代理关系）
  async getAgentOrder(body) {
    // 递归获取所有下级代理关系
    const findAllSubAgents = async (parentAgentId: number, temp: any[] = []): Promise<any[]> => {
      console.log(parentAgentId);
      // 查询直接下级代理
      const agents = await this.agentRelationEntity.createQueryBuilder('a')
        .where('a.parentAgentId = :parentAgentId', { parentAgentId });

      if (temp.length != 0) {
        agents.andWhere('a.parentAgentId NOT IN (:...temp)', { temp });
      }

      const directAgents = await agents.getMany();
      // console.log(temp);
      let allAgents = [...directAgents];
      temp.push(parentAgentId);

      // 递归查询每个直接下级的所有下级
      for (const agent of directAgents) {
        const subAgents = await findAllSubAgents(agent.agentUserId, temp);
        allAgents = [...allAgents, ...subAgents];
      }

      // console.log(allAgents);
      return allAgents;
    };
    // 获取当前用户的代理关系
    const currentAgent = await this.agentRelationEntity.findOne({
      where: {
        agentUserId: this.ctx.admin.userId,
      },
    });

    // 获取当前用户信息
    // const userRes = await this.baseSysUserEntity.findOne({
    //   where: {
    //     id: this.ctx.admin.userId,
    //   },
    // });

    // 获取当前用户关联的店铺ID
    let userShopIds = [];
    if (currentAgent && currentAgent.agentShopIds) {
      userShopIds = currentAgent.agentShopIds.ids || [];
    }

    // 使用递归方式获取所有下级代理关系
    const allSubAgents = await findAllSubAgents(
      currentAgent?.agentUserId || this.ctx.admin.userId
    );

    console.log('allSubAgents', allSubAgents);

    // 根据动态代理关系确定使用的店铺ID集合
    const agentShopIds = new Set<number>();

    // 添加当前用户的店铺ID
    userShopIds.forEach(id => agentShopIds.add(id));

    // 添加所有下级代理的店铺ID
    allSubAgents.forEach(item => {
      if (item.agentShopIds && item.agentShopIds.ids) {
        item.agentShopIds.ids.forEach(id => agentShopIds.add(id));
      }
    });

    console.log('agentShopIds', agentShopIds);

    // 获取所有相关代理用户信息列表
    const levelTwoAgentUserList = [];

    // 收集所有相关的代理商ID
    const allAgentIds = new Set<number>();
    if (currentAgent) {
      allAgentIds.add(currentAgent.agentUserId);
    }
    allSubAgents.forEach(agent => {
      allAgentIds.add(agent.agentUserId);
    });

    console.log('allAgentIds', allAgentIds);

    // 查询所有代理用户信息
    if (allAgentIds.size > 0) {
      const levelTwoAgentUserRes = await this.baseSysUserEntity
        .createQueryBuilder('user')
        .select(['user.id', 'user.name'])
        .where('user.id IN (:...userIds)', {
          userIds: Array.from(allAgentIds),
        })
        .getMany();

      // 构建代理用户信息列表
      levelTwoAgentUserRes.forEach(item => {
        levelTwoAgentUserList.push({
          id: item.id,
          name: item.name || '',
        });
      });
    }

    // 1. 查询订单表 - 添加条件过滤
    let filteredShopIds = Array.from(agentShopIds);
    let filteredUserIds: number[] = [];


    // 处理店铺相关条件过滤 (shopCityId, userPhone, shopId)
    if (body.shopCityId || body.userPhone || body.shopId) {
      const shopConditionQuery = this.orderShopEntity
        .createQueryBuilder('shop')
        .select('shop.id');

      if (body.shopCityId) {
        shopConditionQuery.andWhere('shop.cityId = :shopCityId', {
          shopCityId: body.shopCityId,
        });
      }

      // if (body.userPhone) {
      //   shopConditionQuery.andWhere('shop.phone LIKE :userPhone', {
      //     userPhone: `%${body.userPhone}%`,
      //   });
      // }

      if (body.shopId) {
        shopConditionQuery.andWhere('shop.id = :shopId', {
          shopId: body.shopId,
        });
      }
      const shopConditionResult = await shopConditionQuery.getRawMany();
      console.log('shopConditionResult', shopConditionResult);
      const shopIdsFromCondition = shopConditionResult.map(shop => {
        return shop.shop_id;
      });

      // 交集：只保留同时存在于agentShopIds和条件过滤结果中的店铺ID
      filteredShopIds = filteredShopIds.filter(id =>
        shopIdsFromCondition.includes(id)
      );
    }

    // 构建订单查询
    // 构建订单查询条件
    // 重要：确保只有直接代理或后代代理的店铺订单可被查询
    // 如果没有找到任何授权的店铺ID，直接返回空结果
    if (filteredShopIds.length === 0) {
      return {
        list: [],
        pagination: {
          page: body.page,
          size: body.size,
          total: 0,
        },
      };
    }

    const orderTable = await this.buildOrderQuery(
      body,
      filteredShopIds,
      filteredUserIds
    );

    // 执行订单查询
    const { orders, total } = await this.executeOrderQuery(orderTable, body);

    // 提取所需的关联ID - 使用userId字段
    const userIds = [...new Set(orders.map(order => order.user_id))];

    // 递归----获取关联数据的时候有问题
    // 获取关联数据
    const { shopList, agentList, agentUser } = await this.getRelatedData(
      userIds
    );
    // console.log('allAgent', await this.getRelatedData(userIds));
    // 构建映射关系
    const { shopMap, userMap, agentShopMap } = this.buildMappings(
      shopList,
      agentUser,
      agentList
    );

    // 普通订单
    orders.forEach(order => {
      order.orderType = order.orderType || 'addOrder';
    });

    // 合并关联数据
    const orderRes = this.mergeOrderData(
      orders,
      shopMap,
      userMap,
      agentShopMap
    );

    // 组装返回数据
    const resData = {
      list: orderRes,
      pagination: {
        page: body.page,
        size: body.size,
        total: total,
      },
    };
    return resData;
  }

  /**
   * 构建订单查询条件
   */
  private async buildOrderQuery(body, filteredShopIds, filteredUserIds) {
    const orderTable = this.orderOrderEntity.createQueryBuilder('order');
    // console.log('filteredShopIds', filteredShopIds);
    // 安全过滤：确保用户只能查询到直接代理或后代代理的店铺订单
    // 无论是否为导出模式，都严格应用shopId过滤
    if (filteredShopIds.length > 0) {
      orderTable.andWhere('order.shopId in (:filteredShopIds)', {
        filteredShopIds,
      });
    } else {
      // 当没有找到任何授权的店铺ID时，添加1=0条件确保不返回数据
      orderTable.andWhere('1=0');
    }

    // 只查询已支付的订单
    orderTable.andWhere('order.payStatus = :payStatus', {
      payStatus: 1,
    });

    // 添加订单进度条件
    if (Array.isArray(body.orderProgress)) {
      // 直接使用数组，不要嵌套数组
      orderTable.andWhere('order.orderProgress in (:...orderProgress)', {
        orderProgress: body.orderProgress,
      });
    } else if (
      body.orderProgress !== undefined &&
      body.orderProgress !== null &&
      body.orderProgress !== ''
    ) {
      // 当提供了订单状态且不为空时，使用等于条件过滤
      orderTable.andWhere('order.orderProgress = :orderProgress', {
        orderProgress: body.orderProgress,
      });
    } else if (body.isExport !== true) {
      // 当订单状态为空且不是导出模式时，添加1=0条件确保不返回数据
      orderTable.andWhere('1=0');
    }

    // 代理商订单过滤 - 仅在非导出模式下应用
    if (body.agentUserId && body.isExport !== true) {
      await this.applyAgentFilter(orderTable, body.agentUserId);
    }

    // 处理用户昵称和手机号条件过滤
    if (body.userNickName || body.userPhone) {
      await this.applyUserNickNameFilter(
        orderTable,
        body.userNickName,
        filteredUserIds,
        body.userPhone
      );
    }

    // 添加字段选择
    orderTable.select([
      'order.id as id',
      'order.orderNo as orderNo',
      'order.totalAmount as totalAmount',
      'order.payStatus as payStatus',
      'order.orderTime as orderTime',
      'order.orderType as orderType',
      'order.tongkangOrderTime as tongkangOrderTime',
      'order.shopOrderTime as shopOrderTime',
      'order.orderProgress as orderProgress',
      'order.shopId as shop_id',
      'order.userId as user_id',
    ]);

    return orderTable;
  }

  /**
   * 应用代理商过滤条件
   */
  private async applyAgentFilter(orderTable, agentUserId) {
    // 递归获取所有下级代理关系
    const findAllSubAgents = async (parentAgentId: number, temp: any[] = []): Promise<any[]> => {
      console.log(parentAgentId);
      // 查询直接下级代理
      const agents = await this.agentRelationEntity.createQueryBuilder('a')
        .where('a.parentAgentId = :parentAgentId', { parentAgentId });

      if (temp.length != 0) {
        agents.andWhere('a.parentAgentId NOT IN (:...temp)', { temp });
      }

      const directAgents = await agents.getMany();
      // console.log(temp);
      let allAgents = [...directAgents];
      temp.push(parentAgentId);

      // 递归查询每个直接下级的所有下级
      for (const agent of directAgents) {
        const subAgents = await findAllSubAgents(agent.agentUserId, temp);
        allAgents = [...allAgents, ...subAgents];
      }

      // console.log(allAgents);
      return allAgents;
    };

    const agentUserRes = await this.agentRelationEntity
      .createQueryBuilder('agentRelation')
      .select('agentShopIds')
      .where('agentRelation.agentUserId = :agentUserId', {
        agentUserId,
      })
      .getRawOne();

    let shopIds = [];

    // 检查是否有直接的shopIds
    if (
      agentUserRes?.agentShopIds?.ids &&
      agentUserRes.agentShopIds.ids.length > 0
    ) {
      shopIds = agentUserRes.agentShopIds.ids;
    } else {
      // 当ids为空时，获取该代理商的所有后代代理的shopIds
      const allSubAgents = await findAllSubAgents(agentUserId);

      if (allSubAgents && allSubAgents.length > 0) {
        // 收集所有后代代理的shopIds
        const descendantAgentIds = allSubAgents.map(agent => agent.agentUserId);

        if (descendantAgentIds.length > 0) {
          const descendantShopRes = await this.agentRelationEntity
            .createQueryBuilder('agentRelation')
            .select('agentShopIds')
            .where('agentRelation.agentUserId IN (:...descendantAgentIds)', {
              descendantAgentIds,
            })
            .getRawMany();

          // 合并所有后代代理的shopIds
          descendantShopRes.forEach(res => {
            // 处理agentShopIds可能是对象包含ids数组或直接是数组的情况
            const ids = Array.isArray(res.agentShopIds)
              ? res.agentShopIds
              : res?.agentShopIds?.ids
              ? res.agentShopIds.ids
              : [];

            if (ids.length > 0) {
              shopIds = [...shopIds, ...ids];
            }
          });
        }
      }
    }

    // 只有当shopIds数组不为空时才添加IN条件，否则添加一个永远不会匹配的条件
    if (shopIds.length > 0) {
      orderTable.andWhere('order.shopId IN (:...shopIds)', {
        shopIds,
      });
    } else {
      // 当没有找到任何关联的shopIds时，添加一个永远不会匹配的条件，确保不会返回任何数据
      orderTable.andWhere('1 = 0');
    }
  }

  /**
   * 应用用户昵称过滤条件
   */
  private async applyUserNickNameFilter(
    orderTable,
    userNickName,
    filteredUserIds,
    userPhone = ''
  ) {
    // 构建查询条件
    const queryBuilder = this.userInfoEntity
      .createQueryBuilder('user')
      .select('user.id');

    // 添加昵称过滤条件
    if (userNickName) {
      queryBuilder.where('user.nickName LIKE :userNickName', {
        userNickName: `%${userNickName}%`,
      });
    }

    // 添加手机号过滤条件
    if (userPhone) {
      if (userNickName) {
        queryBuilder.orWhere('user.phone LIKE :userPhone', {
          userPhone: `%${userPhone}%`,
        });
      } else {
        queryBuilder.where('user.phone LIKE :userPhone', {
          userPhone: `%${userPhone}%`,
        });
      }
    }

    const userConditionResult = await queryBuilder.getRawMany();

    userConditionResult.forEach(item => {
      filteredUserIds.push(item.user_id);
    });

    // 当提供了用户昵称或手机号但没有匹配到用户时，添加1=0条件确保返回空结果
    if ((userNickName || userPhone) && filteredUserIds.length === 0) {
      orderTable.andWhere('1=0');
    } else if (filteredUserIds.length > 0) {
      // 只有当filteredUserIds数组不为空时才添加IN条件 - 使用userId字段
      orderTable.andWhere('order.userId IN (:filteredUserIds)', {
        filteredUserIds,
      });
    }
  }

  /**
   * 执行订单查询
   */
  private async executeOrderQuery(orderTable, body) {
    const total = await orderTable.getCount();
    let orders;

    if (body.isExport == true) {
      // 导出模式：获取所有数据，不进行分页
      console.log('导出模式 - 订单查询SQL:', orderTable.getSql());
      console.log('导出模式 - 过滤条件:', {
        payStatus: body.payStatus,
        isAgent: body.isAgent,
      });
      orders = await orderTable.getRawMany();
    } else if (body.page && body.size) {
      // 分页查询模式
      orders = await orderTable
        .skip((body.page - 1) * body.size)
        .orderBy('order.shopOrderTime IS NULL', 'DESC')
        .addOrderBy(body.order || 'id', (body.sort || 'DESC').toUpperCase())
        .take(body.size)
        .getRawMany();
      console.log('分页查询模式 - 订单查询SQL:', orderTable.getSql());
    } else {
      // 不分页查询
      orders = await orderTable.getRawMany();
    }

    return { orders, total };
  }

  /**
   * 获取关联数据（使用动态代理关系）
   */
  private async getRelatedData(userIds) {
    // console.log('userIds', userIds);
    // 递归获取所有下级代理关系
    const findAllSubAgents = async (parentAgentId: number, temp: any[] = []): Promise<any[]> => {
      // 查询直接下级代理
      const agents = await this.agentRelationEntity.createQueryBuilder('a')
        .where('a.parentAgentId = :parentAgentId', { parentAgentId });

      if (temp.length != 0) {
        agents.andWhere('a.parentAgentId NOT IN (:...temp)', { temp });
      }

      const directAgents = await agents.getMany();
      // console.log(temp);
      let allAgents = [...directAgents];
      temp.push(parentAgentId);

      // 递归查询每个直接下级的所有下级
      for (const agent of directAgents) {
        const subAgents = await findAllSubAgents(agent.agentUserId, temp);
        allAgents = [...allAgents, ...subAgents];
      }
      // console.log('directAgents', directAgents);
      return allAgents;
    };

    // 获取当前用户的代理关系
    let currentAgents = await this.agentRelationEntity.find({
      where: {
        agentUserId: this.ctx.admin.userId,
      },
    });

    // 获取所有下级代理关系
    let allSubAgents = [];

    // 如果找到以agentUserId匹配的代理关系
    if (currentAgents && currentAgents.length > 0) {
      // 为每个找到的代理收集其下级代理
      for (const agent of currentAgents) {
        const subAgents = await findAllSubAgents(agent.agentUserId);
        allSubAgents = [...allSubAgents, ...subAgents];
      }
    } else {
      // 尝试以parentAgentId查找所有一级代理（支持多个一级代理）
      const levelOneAgents = await this.agentRelationEntity.find({
        where: {
          parentAgentId: this.ctx.admin.userId,
        },
      });

      // 为每个一级代理收集其下级代理
      for (const agent of levelOneAgents) {
        const subAgents = await findAllSubAgents(agent.agentUserId);
        allSubAgents = [...allSubAgents, ...subAgents];
      }

      // 将一级代理也添加到currentAgents中
      currentAgents = levelOneAgents;
    }

    // 收集所有相关的代理商ID
    const allAgentIds = new Set<number>();

    // 添加所有一级代理的ID
    if (currentAgents && currentAgents.length > 0) {
      currentAgents.forEach(agent => {
        allAgentIds.add(agent.agentUserId);
      });
    }

    // 添加所有下级代理的ID
    allSubAgents.forEach(agent => {
      allAgentIds.add(agent.agentUserId);
    });

    // 获取店铺数据
    const shops = this.orderShopEntity
      .createQueryBuilder('shop')
      .select([
        'shop.id as id',
        'shop.name as name',
        'shop.address as address',
        'shop.phone as phone',
        'shop.cityId as cityId',
      ]);
    const shopList = await shops.getRawMany();

    // 获取动态代理关系数据
    const agentList = [];
    if (allAgentIds.size > 0) {
      const agentRelationRes = await this.agentRelationEntity
        .createQueryBuilder('agent')
        .where('agent.agentUserId IN (:...agentIds)', {
          agentIds: Array.from(allAgentIds),
        })
        .getRawMany();
      agentList.push(...agentRelationRes);
    }

    // 获取用户数据 - 从user_info表获取
    let agentUser = [];
    // 只有当用户ID集合不为空时才执行查询
    if (userIds.length > 0) {
      agentUser = await this.userInfoEntity
        .createQueryBuilder('user')
        .select([
          'user.id as id',
          'user.nickName as name',
          'user.phone as phone',
        ])
        .where('user.id IN (:...userIds)', { userIds: Array.from(userIds) })
        .getRawMany();
    }

    return { shopList, agentList, agentUser };
  }

  /**
   * 构建映射关系（使用动态代理关系）
   */
  private buildMappings(shopList, agentUser, agentList) {
    // 店铺映射
    const shopMap = new Map(shopList.map(shop => [shop.id, shop]));

    // 用户映射
    const userMap = new Map(agentUser.map(user => [user.id, user]));

    // 代理商店铺映射关系 - 基于动态代理关系
    const agentShopMap = new Map();
    // console.log('agentList', agentList);
    // 处理所有代理商的店铺映射
    agentList.forEach(agent => {
      // 获取当前代理商ID
      const currentAgentId =
        agent.agent_agentUserId || agent.agentUserId || agent.id;
      // 处理当前代理商的店铺
      if (
        agent.agent_agentShopIds &&
        agent.agent_agentShopIds.ids &&
        Array.isArray(agent.agent_agentShopIds.ids)
      ) {
        agent.agent_agentShopIds.ids.forEach(shopId => {
          // 将店铺直接映射到当前代理商，使用实际的代理关系
          // 不再查找顶级代理，而是尊重实际的代理层级结构
          agentShopMap.set(shopId, currentAgentId);
        });
      }
    });
    return { shopMap, userMap, agentShopMap };
  }

  /**
   * 查找顶级代理商ID
   * @param agentId 当前代理商ID
   * @param agentRelationMap 代理关系映射
   * @returns 顶级代理商ID
   */
  private findTopAgent(agentId, agentRelationMap) {
    let currentId = agentId;
    let topId = agentId;

    // 最多递归查找10层，防止死循环
    const maxDepth = 10;
    let depth = 0;

    // 递归查找上级代理，直到找到顶级代理
    while (depth < maxDepth) {
      const agent = agentRelationMap.get(currentId);
      if (!agent) {
        // 没有找到对应的代理关系，当前即为顶级代理
        break;
      }

      // 如果存在上级代理，则继续向上查找
      if (
        agent.agent_parentAgentUserId &&
        agent.agent_parentAgentUserId !== currentId
      ) {
        topId = agent.agent_parentAgentUserId;
        currentId = agent.agent_parentAgentUserId;
      } else {
        // 没有上级代理，当前即为顶级代理
        break;
      }

      depth++;
    }

    return topId;
  }

  /**
   * 合并订单数据
   */
  private mergeOrderData(orders, shopMap, userMap, agentShopMap) {
    // console.log('agentShopMap', agentShopMap);
    return orders.map(order => {
      const shop = shopMap.get(order.shop_id) || {};
      // 使用userId字段关联用户信息
      const user = userMap.get(order.user_id) || {};

      // 获取代理商ID，如果店铺未关联代理商，则返回0
      // 这是导致agentUserId有时等于0的原因
      const agentUserId = agentShopMap.get(order.shop_id) || 0;

      return {
        id: order.id,
        orderNo: order.orderNo,
        totalAmount: order.totalAmount,
        payStatus: order.payStatus,
        orderTime: order.orderTime,
        tongkangOrderTime: order.tongkangOrderTime,
        shopOrderTime: order.shopOrderTime,
        orderProgress: order.orderProgress,
        orderType: order.orderType,
        shop_id: order.shop_id,
        shopName: shop.name || '',
        shopAddress: shop.address || '',
        userPhone: user.phone || '',
        shopCityId: shop.cityId || 0,
        userNickName: user.name || '',
        agentUserId: agentUserId,
      };
    });
  }

  // 代理商看板
  async agentBoard(params) {
    console.log('params', params);
    // 递归获取所有下级代理关系
    const findAllSubAgents = async (parentAgentId: number): Promise<any[]> => {
      // 查询直接下级代理
      const directAgents = await this.agentRelationEntity.find({
        where: {
          parentAgentId: parentAgentId,
        },
      });

      let allAgents = [...directAgents];

      // 递归查询每个直接下级的所有下级
      for (const agent of directAgents) {
        const subAgents = await findAllSubAgents(agent.agentUserId);
        allAgents = [...allAgents, ...subAgents];
      }

      return allAgents;
    };

    // 获取当前用户的代理关系
    const currentAgent = await this.agentRelationEntity.findOne({
      where: {
        agentUserId: 1,
      },
    });

    // 获取当前用户关联的店铺ID
    let userShopIds = [];
    if (currentAgent && currentAgent.agentShopIds) {
      userShopIds = currentAgent.agentShopIds.ids || [];
    }

    // 使用递归方式获取所有下级代理关系
    const allSubAgents = await findAllSubAgents(
      currentAgent?.agentUserId || 1
    );

    // 根据动态代理关系确定使用的店铺ID集合
    const agentShopIds = new Set<number>();

    // 添加当前用户的店铺ID
    userShopIds.forEach(id => agentShopIds.add(id));

    // 添加所有下级代理的店铺ID
    allSubAgents.forEach(item => {
      if (item.agentShopIds && item.agentShopIds.ids) {
        item.agentShopIds.ids.forEach(id => agentShopIds.add(id));
      }
    });

    // 收集所有代理商信息
    const allAgents = [];
    if (currentAgent) {
      allAgents.push(currentAgent);
    }
    allAgents.push(...allSubAgents);

    let agentBoardResList = [];

    // 代理商店铺订单
    const orderRes = await this.orderOrderEntity
      .createQueryBuilder('order')
      .leftJoin(OrderShopEntity, 'shop', 'shop.id = order.shopId')
      .leftJoin(OrderCityEntity, 'city', 'city.id = shop.cityId')
      .select([
        'order.id as id',
        'order.orderNo',
        'order.totalAmount as totalAmount',
        'order.payStatus',
        'order.orderTime',
        'order.tongkangOrderTime as tongkangOrderTime',
        'order.shopOrderTime as shopOrderTime',
        'order.orderProgress as orderProgress',
        'order.payAmount as payAmount',
        'shop.id as shop_id',
        'shop.name as shopName',
        'shop.address as shopAddress',
        'shop.phone as userPhone',
        'shop.cityId as shopCityId',
      ])
      .where('order.payStatus = 1'); // 只查询已支付的订单

    // 只查询正常订单，客情订单不统计
    orderRes.andWhere('(orderType is null or orderType = :orderType)', {
      orderType: 'addOrder',
    });

    const shopIdArray = Array.from(agentShopIds);
    if (shopIdArray.length != 0) {
      // 代理商店铺不为空
      orderRes.andWhere('shop.id IN (:...agentShopIds)', {
        agentShopIds: shopIdArray,
      });
    } else {
      // 代理商店铺为空
      orderRes.andWhere('1 = 100000');
    }

    // 获取订单数据
    const orderData = await orderRes.getRawMany();

    // 转换数据为AgentBoardDict格式
    const agentInfoMap = new Map<any, any>();

    // 获取所有代理商的用户信息
    const userInfoMap = new Map<any, any>();
    let userIds = [];
    for (const agent of allAgents) {
      userIds.push(agent.agentUserId);
    }
    const agentUserInfo = await this.baseSysUserEntity.find({
      where: {
        id: In(userIds),
      },
    });
    const agentMap = new Map<any, any>();
    allAgents.forEach(item => {
      agentMap.set(item.agentUserId, item);
    });
    // 递归获取当前代理商层级
    // const agentLevel = (userId: number, level = 1): number => {
    //   const parentAgentId = agentMap.get(userId)?.parentAgentId || 0;
    //   if (parentAgentId != 0 && parentAgentId != 1) {
    //     level = agentLevel(parentAgentId, level + 1);
    //   }
    //   return level;
    // };
    agentUserInfo.forEach(item => {
      userInfoMap.set(item.id, item);
      // 存储代理商信息
      agentInfoMap.set(item.id, {
        agentUserId: item.id,
        agentName: item.name || '未知代理商',
        shopIds: agentMap.get(item.id)?.agentShopIds?.ids || [],
        parentAgentId: agentMap.get(item.id)?.parentAgentId || 0,
        agentLevel: agentMap.get(item.id)?.level || 1,
        // agentLevel: agentLevel(item.id),
      });
    });

    const shop = await this.orderShopEntity.find({
      where: {
        id: In(shopIdArray),
      },
    });

    const shopMap = new Map<any, any>();
    shop.forEach(item => {
      shopMap.set(item.id, item);
    });

    // 店铺id: 订单数组
    const agentShopOrderMap = new Map<any, any>();

    // 遍历订单数据，将订单分配到对应的代理商店铺
    orderData.forEach(order => {
      const shopId = order.shop_id;
      if (shopIdArray.includes(shopId)) {
        if (!agentShopOrderMap.has(shopId)) {
          agentShopOrderMap.set(shopId, []);
        }
        agentShopOrderMap.get(shopId)?.push(order);
      }
    });

    // 获取代理商层级深度
    let agentLevel = 1;
    for (const agent of allAgents) {
      agentLevel = Math.max(agentLevel, agent.level || 1);
    }

    let resBoardData = [];

    const getOrderCountAndTotal = (orders: any[]) => {
      let orderCount = 0;
      let totalAmount = 0;
      orders.forEach(order => {
        orderCount++;
        totalAmount += Number(order.totalAmount);
      });
      return { orderCount, totalAmount };
    };

    const getAgentLevel = (userId: number, tempDict): Object => {
      const parentAgentId = agentInfoMap.get(userId)?.parentAgentId;
      let userInfo = agentInfoMap.get(userId);
      if (parentAgentId) {
        tempDict["level-" + userInfo.agentLevel] = userInfo.agentName;
        getAgentLevel(parentAgentId, tempDict);
      }
      return tempDict;
    };

    for (const agent of agentInfoMap) {
      for (const shopId of agent[1].shopIds) {
        let agentLevelDict = getAgentLevel(agent[1].agentUserId, {});
        let { orderCount, totalAmount } = getOrderCountAndTotal(agentShopOrderMap.get(shopId) || []);
        resBoardData.push({
          id: agent[1].agentUserId,
          ...agentLevelDict,
          shopName: shopMap.get(shopId)?.name || '未知店铺',
          orderCount,
          totalAmount,
        });
      }
    }

    return {
      tableData: resBoardData,
      maxAgentLevel: agentLevel,
    };
  }

  // 门店数据看板
  async agentShopBoard(params) {
    // 递归获取所有下级代理关系
    const findAllSubAgents = async (parentAgentId: number, temp: any[] = []): Promise<any[]> => {
      console.log(parentAgentId);
      // 查询直接下级代理
      const agents = await this.agentRelationEntity.createQueryBuilder('a')
        .where('a.parentAgentId = :parentAgentId', { parentAgentId });

      if (temp.length != 0) {
        agents.andWhere('a.parentAgentId NOT IN (:...temp)', { temp });
      }

      const directAgents = await agents.getMany();
      // console.log(temp);
      let allAgents = [...directAgents];
      temp.push(parentAgentId);

      // 递归查询每个直接下级的所有下级
      for (const agent of directAgents) {
        const subAgents = await findAllSubAgents(agent.agentUserId, temp);
        allAgents = [...allAgents, ...subAgents];
      }

      // console.log(allAgents);
      return allAgents;
    };

    // 获取当前用户的代理关系
    const currentAgent = await this.agentRelationEntity.findOne({
      where: {
        agentUserId: this.ctx.admin?.userId,
      },
    });

    // 获取当前用户关联的店铺ID
    let userShopIds = [];
    if (currentAgent && currentAgent.agentShopIds) {
      userShopIds = currentAgent.agentShopIds.ids || [];
    }

    // 使用递归方式获取所有下级代理关系
    const allSubAgents = await findAllSubAgents(
      currentAgent?.agentUserId || this.ctx.admin.userId
    );

    // 根据动态代理关系确定使用的店铺ID集合
    const agentShopIds = new Set<number>();

    // 添加当前用户的店铺ID
    userShopIds.forEach(id => agentShopIds.add(id));

    // 添加所有下级代理的店铺ID
    allSubAgents.forEach(item => {
      if (item.agentShopIds && item.agentShopIds.ids) {
        item.agentShopIds.ids.forEach(id => agentShopIds.add(id));
      }
    });

    // 收集所有代理商信息
    const allAgents = [];
    if (currentAgent) {
      allAgents.push(currentAgent);
    }
    allAgents.push(...allSubAgents);

    let agentBoardResList = [];

    // 代理商店铺订单
    const orderRes = await this.orderOrderEntity
      .createQueryBuilder('order')
      .leftJoin(OrderShopEntity, 'shop', 'shop.id = order.shopId')
      .leftJoin(OrderCityEntity, 'city', 'city.id = shop.cityId')
      .select([
        'order.id as id',
        'order.orderNo',
        'order.totalAmount as totalAmount',
        'order.payStatus',
        'order.orderTime',
        'order.tongkangOrderTime as tongkangOrderTime',
        'order.shopOrderTime as shopOrderTime',
        'order.orderProgress as orderProgress',
        'shop.id as shop_id',
        'shop.name as shopName',
        'shop.address as shopAddress',
        'shop.phone as userPhone',
        'shop.cityId as shopCityId',
      ])
      .where('order.payStatus = 1'); // 只查询已支付的订单

    // 只查询正常订单，客情订单不统计
    orderRes.andWhere('orderType is null or orderType = :orderType', {
      orderType: 'addOrder',
    });

    const shopIdArray = Array.from(agentShopIds);
    if (shopIdArray.length != 0) {
      // 代理商店铺不为空
      orderRes.andWhere('shop.id IN (:...agentShopIds)', {
        agentShopIds: shopIdArray,
      });
    } else {
      // 代理商店铺为空
      orderRes.andWhere('1 = 100000');
    }

    // 获取订单数据
    const orderData = await orderRes.getRawMany();
    // console.log('orderData', orderData);
    // 转换数据为AgentBoardDict格式
    // 1. 获取城市信息
    const cityList = await this.orderCityEntity.find();
    const cityMap = new Map<any, any>(
      cityList.map((city: any) => [city.id, city.cityName])
    );

    // 2. 获取代理商店铺关系映射和代理商信息映射
    const agentShopMap = new Map<any, any>();
    const agentInfoMap = new Map<any, any>();

    // 获取所有代理商的用户信息
    const userInfoMap = new Map<any, any>();
    for (const agent of allAgents) {
      const userInfo = await this.baseSysUserEntity.findOne({
        where: {
          id: agent.agentUserId,
        },
      });
      userInfoMap.set(agent.agentUserId, userInfo);

      // 存储代理商信息
      agentInfoMap.set(agent.agentUserId, {
        agentUserId: agent.agentUserId,
        agentName: userInfo?.name || '未知代理商',
      });
    }

    // 构建代理商店铺映射
    for (const agent of allAgents) {
      // 修复：agentShopIds可能是对象包含ids数组或直接是数组
      const shopIds = Array.isArray(agent.agentShopIds)
        ? agent.agentShopIds
        : agent.agentShopIds && agent.agentShopIds.ids
        ? agent.agentShopIds.ids
        : [];

      shopIds.forEach((shopId: any) => {
        agentShopMap.set(shopId, {
          agentUserId: agent.agentUserId,
          agentName: userInfoMap.get(agent.agentUserId)?.name || '未知代理商',
        });
      });
    }

    // 3. 按城市和店铺分组统计订单数据
    const cityShopMap = new Map<any, any>();

    // 先初始化所有代理商信息，确保即使没有订单也能显示
    for (const agent of allAgents) {
      const agentUserId = agent.agentUserId;
      const agentName = userInfoMap.get(agentUserId)?.name || '未知代理商';

      // 修复：agentShopIds可能是对象包含ids数组或直接是数组
      const shopIds = Array.isArray(agent.agentShopIds)
        ? agent.agentShopIds
        : agent.agentShopIds && agent.agentShopIds.ids
        ? agent.agentShopIds.ids
        : [];

      // 获取每个店铺的城市信息
      for (const shopId of shopIds) {
        const shop = await this.orderShopEntity.findOne({
          where: { id: shopId },
        });

        if (shop && shop.cityId) {
          const cityId = shop.cityId;

          // 初始化城市数据
          if (!cityShopMap.has(cityId)) {
            cityShopMap.set(cityId, {
              cityId: cityId,
              cityName: cityMap.get(cityId) || '',
              agentMap: new Map(),
            });
          }

          const cityData = cityShopMap.get(cityId);

          // 初始化代理商数据
          if (!cityData.agentMap.has(agentUserId)) {
            cityData.agentMap.set(agentUserId, {
              agentUserId: agentUserId,
              agentName: agentName,
              amount: 0,
              shopArr: new Map(),
            });
          }

          const agentData = cityData.agentMap.get(agentUserId);

          // 初始化店铺数据
          if (!agentData.shopArr.has(shopId)) {
            agentData.shopArr.set(shopId, {
              shopId: shopId,
              shopName: shop.name || '',
              orderCount: 0,
              amount: 0,
            });
          }
        }
      }
    }

    // 确保所有代理（包括子代理）都被添加到对应的城市agentMap中
    // 即使代理没有自己的店铺，也需要被添加以便显示在children中
    // 首先预加载所有店铺信息，避免在循环中使用await
    const shopInfoMap = new Map<number, any>();
    const allShopIds = new Set<number>();

    // 收集所有需要查询的店铺ID
    allAgents.forEach(agent => {
      const shopIds = Array.isArray(agent.agentShopIds)
        ? agent.agentShopIds
        : agent.agentShopIds && agent.agentShopIds.ids
        ? agent.agentShopIds.ids
        : [];
      shopIds.forEach(id => allShopIds.add(id));
    });

    // 批量查询所有店铺信息
    if (allShopIds.size > 0) {
      const shops = await this.orderShopEntity.find({
        where: {
          id: In(Array.from(allShopIds)),
        },
      });
      shops.forEach(shop => shopInfoMap.set(shop.id, shop));
    }

    // 现在可以同步处理代理关系
    allAgents.forEach(agent => {
      const agentUserId = agent.agentUserId;
      const agentName = userInfoMap.get(agentUserId)?.name || '未知代理商';

      // 获取该代理所有下级代理的店铺城市信息
      allSubAgents.forEach(subAgent => {
        // 如果是当前代理的下级代理
        if (subAgent.parentAgentId === agentUserId) {
          // 修复：agentShopIds可能是对象包含ids数组或直接是数组
          const shopIds = Array.isArray(subAgent.agentShopIds)
            ? subAgent.agentShopIds
            : subAgent.agentShopIds && subAgent.agentShopIds.ids
            ? subAgent.agentShopIds.ids
            : [];

          // 遍历下级代理的店铺，将当前代理添加到对应的城市中
          for (const shopId of shopIds) {
            const shop = shopInfoMap.get(shopId);

            if (shop && shop.cityId) {
              const cityId = shop.cityId;

              // 确保城市数据存在
              if (!cityShopMap.has(cityId)) {
                cityShopMap.set(cityId, {
                  cityId: cityId,
                  cityName: cityMap.get(cityId) || '',
                  agentMap: new Map(),
                });
              }

              const cityData = cityShopMap.get(cityId);

              // 确保当前代理在该城市的agentMap中
              if (!cityData.agentMap.has(agentUserId)) {
                cityData.agentMap.set(agentUserId, {
                  agentUserId: agentUserId,
                  agentName: agentName,
                  amount: 0,
                  shopArr: new Map(),
                });
              }
            }
          }
        }
      });
    });

    // 处理订单数据，更新统计信息
    orderData.forEach((order: any) => {
      const cityId = order.shopCityId;
      const shopId = order.shop_id;
      const totalAmount = Number(order.totalAmount || 0);

      // 只有当城市数据已经存在时才处理订单数据
      // 确保shopCityId与最外层数据的shopCityId一致
      if (cityShopMap.has(cityId)) {
        const cityData = cityShopMap.get(cityId);
        // 获取店铺对应的代理商信息
        const agentInfo = agentShopMap.get(shopId) || {
          agentUserId: null,
          agentName: '',
        };

        // 初始化代理商数据（如果之前没处理到的情况）
        if (!cityData.agentMap.has(agentInfo.agentUserId)) {
          cityData.agentMap.set(agentInfo.agentUserId, {
            agentUserId: agentInfo.agentUserId,
            agentName: agentInfo.agentName,
            amount: 0,
            shopArr: new Map(),
          });
        }

        const agentData = cityData.agentMap.get(agentInfo.agentUserId);

        // 初始化店铺数据（如果之前没处理到的情况）
        if (!agentData.shopArr.has(shopId)) {
          agentData.shopArr.set(shopId, {
            shopId: shopId,
            shopName: order.shopName || '',
            orderCount: 0,
            amount: 0,
          });
        }

        // 更新店铺统计数据
        const shopData = agentData.shopArr.get(shopId);
        shopData.orderCount++;
        shopData.amount += totalAmount;
        agentData.amount += totalAmount;
      }
    });

    // 4. 构建最终返回格式 - 树形结构
    agentBoardResList = Array.from(cityShopMap.values()).map(cityData => {
      // 构建代理关系映射，用于快速查找下级代理
      const agentParentMap = new Map<number, number[]>();

      // 构建所有代理之间的层级关系
      // 确保包含allSubAgents中的代理
      [...allAgents, ...allSubAgents].forEach(agent => {
        const agentUserId = agent.agentUserId;
        if (agent.parentAgentId && agent.parentAgentId > 0) {
          const parentAgentId = agent.parentAgentId;
          if (!agentParentMap.has(parentAgentId)) {
            agentParentMap.set(parentAgentId, []);
          }
          // 避免重复添加
          if (!agentParentMap.get(parentAgentId)!.includes(agentUserId)) {
            agentParentMap.get(parentAgentId)!.push(agentUserId);
          }
        }
      });

      // 额外处理，确保直接在allSubAgents中的代理也被正确映射
      allSubAgents.forEach(subAgent => {
        const agentUserId = subAgent.agentUserId;
        if (subAgent.parentAgentId && subAgent.parentAgentId > 0) {
          const parentAgentId = subAgent.parentAgentId;
          if (!agentParentMap.has(parentAgentId)) {
            agentParentMap.set(parentAgentId, []);
          }
          // 避免重复添加
          if (!agentParentMap.get(parentAgentId)!.includes(agentUserId)) {
            agentParentMap.get(parentAgentId)!.push(agentUserId);
          }
        }
      });

      // 构建代理树形结构的递归函数
      const buildAgentTree = (parentAgentId: number): any[] => {
        const childAgentIds = agentParentMap.get(parentAgentId) || [];

        return childAgentIds
          .map(agentId => {
            // 在所有城市中查找代理数据，而不仅限于当前城市
            let agentData = cityData.agentMap.get(agentId);

            // // 如果当前城市没有该代理的数据，尝试在其他城市查找
            // if (!agentData) {
            //   for (const otherCityData of cityShopMap.values()) {
            //     if (otherCityData.agentMap.has(agentId)) {
            //       agentData = otherCityData.agentMap.get(agentId);
            //       break;
            //     }
            //   }
            // }

            // 如果仍然找不到代理数据，尝试创建一个基本的代理数据
            if (!agentData) {
              const agentName = userInfoMap.get(agentId)?.name || '未知代理商';
              agentData = {
                agentUserId: agentId,
                agentName: agentName,
                amount: 0,
                shopArr: new Map(),
              };
            }

            const children = buildAgentTree(Number(agentId));

            return {
              amount: agentData.amount || 0,
              agentName: agentData.agentName,
              agentUserId: agentData.agentUserId,
              shopArr:
                agentData.shopArr instanceof Map
                  ? Array.from(agentData.shopArr.values())
                  : agentData.shopArr || [],
              children: children.filter(Boolean), // 过滤掉null值
            };
          })
          .filter(Boolean); // 过滤掉null值
      };

      // 获取当前用户作为根代理（如果有）
      const currentAgentId = currentAgent?.agentUserId || this.ctx.admin.userId;

      // 构建树形结构，确保数据格式符合要求
      const agentArr = [];

      // 优先处理当前用户 - 在所有城市中查找代理数据
      let currentUserData = cityData.agentMap.get(currentAgentId);
      if (!currentUserData) {
        for (const otherCityData of cityShopMap.values()) {
          if (otherCityData.agentMap.has(currentAgentId)) {
            currentUserData = otherCityData.agentMap.get(currentAgentId);
            break;
          }
        }
      }

      if (!currentUserData) {
        const agentName = userInfoMap.get(currentAgentId)?.name || '未知代理商';
        currentUserData = {
          agentUserId: currentAgentId,
          agentName: agentName,
          amount: 0,
          shopArr: new Map(),
        };
      }

      // 添加当前用户到agentArr
      const currentUserChildren = buildAgentTree(Number(currentAgentId));
      agentArr.push({
        amount: currentUserData.amount || 0,
        agentName: currentUserData.agentName,
        agentUserId: currentUserData.agentUserId,
        shopArr:
          currentUserData.shopArr instanceof Map
            ? Array.from(currentUserData.shopArr.values())
            : currentUserData.shopArr || [],
        children: currentUserChildren,
      });

      // 处理其他一级代理（不在当前城市数据中的一级代理也需要考虑）
      // 从所有代理中找出一级代理
      const allFirstLevelAgents = new Set<number>();

      // 方法1: 从allAgents和allSubAgents中找出没有上级代理的代理
      [...allAgents, ...allSubAgents].forEach(agent => {
        if (!agent.parentAgentId || agent.parentAgentId === 0) {
          allFirstLevelAgents.add(agent.agentUserId);
        }
      });

      // 方法2: 找出所有不在任何parentAgentMap值中的代理ID
      const allChildAgentIds = new Set<number>();
      agentParentMap.forEach(children => {
        children.forEach(id => allChildAgentIds.add(id));
      });

      [...allAgents, ...allSubAgents].forEach(agent => {
        if (!allChildAgentIds.has(agent.agentUserId)) {
          allFirstLevelAgents.add(agent.agentUserId);
        }
      });

      // 过滤掉已经添加的当前用户
      const otherFirstLevelAgents = Array.from(allFirstLevelAgents).filter(
        agentId => agentId !== currentAgentId
      );

      // 添加其他一级代理
      otherFirstLevelAgents.forEach(agentId => {
        // 在所有城市中查找代理数据
        let agentData = cityData.agentMap.get(agentId);
        if (!agentData) {
          for (const otherCityData of cityShopMap.values()) {
            if (otherCityData.agentMap.has(agentId)) {
              agentData = otherCityData.agentMap.get(agentId);
              break;
            }
          }
        }

        if (!agentData) {
          const agentName = userInfoMap.get(agentId)?.name || '未知代理商';
          agentData = {
            agentUserId: agentId,
            agentName: agentName,
            amount: 0,
            shopArr: new Map(),
          };
        }

        const children = buildAgentTree(Number(agentId));

        agentArr.push({
          amount: agentData.amount || 0,
          agentName: agentData.agentName,
          agentUserId: agentData.agentUserId,
          shopArr:
            agentData.shopArr instanceof Map
              ? Array.from(agentData.shopArr.values())
              : agentData.shopArr || [],
          children: children,
        });
      });

      // 计算城市总金额和总订单数
      let totalAmount = 0;
      let totalOrderCount = 0;

      // 递归计算统计数据
      const calculateStats = (agents: any[]) => {
        agents.forEach(agent => {
          totalAmount += agent.amount;
          agent.shopArr.forEach((shop: any) => {
            totalOrderCount += shop.orderCount;
          });
          if (agent.children && agent.children.length > 0) {
            calculateStats(agent.children);
          }
        });
      };

      calculateStats(agentArr);

      return {
        cityId: cityData.cityId,
        cityName: cityData.cityName,
        orderCount: totalOrderCount,
        amount: totalAmount,
        agentArr: agentArr,
      };
    });
    // console.log(agentBoardResList);
    return agentBoardResList;
  }

  // 获取店铺订单
  async getOrderShopList() {
    const AgentRes = await this.agentRelationEntity.findOne({
      where: {
        agentUserId: this.ctx.admin.userId,
      },
    });
    if (AgentRes) {
      return AgentRes.agentShopIds.ids;
    }
    const adminId = this.ctx.admin.userId;
    const admin = await this.baseSysUserEntity.findOne({
      where: {
        id: adminId,
      },
    });
    if (!admin.shopId) {
      return [];
    }
    return [admin.shopId];
  }

  // 代理商商铺信息
  async getAgentShopList(body) {
    const AgentRes = await this.agentRelationEntity.findOne({
      where: {
        agentUserId: this.ctx.admin.userId,
      },
    });
    if (!AgentRes) {
      const adminId = this.ctx.admin.userId;
      const admin = await this.baseSysUserEntity.findOne({
        where: {
          id: adminId,
        },
      });
      const shopList = await this.orderShopEntity.find({
        where: {
          id: In([admin.shopId]),
        },
      });
      // console.log(shopList);
      if (shopList.length > 0) {
        return shopList;
      }
      throw new Error('该用户没配置店铺');
    } else if (Array.isArray(AgentRes.agentShopIds.ids)) {
      const shopList = await this.orderShopEntity.find({
        where: {
          id: In(AgentRes.agentShopIds.ids),
        },
      });
      // console.log(shopList);
      return shopList;
    }
    return '';
  }

  // 查询代理关系v2
  async queryAgentRelationV2(body) {
    const agentRelationres = await this.agentRelationEntity
      .createQueryBuilder('a')
      .leftJoin('base_sys_user', 'u', 'u.id = a.agentUserId')
      .select([
        'a.agentUserId',
        'a.level',
        'a.agentShopIds',
        'a.parentAgentId',
        'u.*',
      ])
      .getRawMany();

    // 收集所有有效的店铺ID
    const allShopIds = agentRelationres
      .map(item => item.agentShopIds?.ids)
      .flat()
      .filter(id => id !== null && id !== undefined && id !== '');

    // 查询所有相关店铺信息
    const shopList = await this.orderShopEntity.find({
      where: { id: In(allShopIds) },
    });

    // 将店铺数据转换为以id为键的对象，方便查找
    const shopMap = shopList.reduce((map, shop) => {
      map[shop.id] = shop;
      return map;
    }, {});

    // 转换为以agentUserId为键的对象格式
    const result = agentRelationres.reduce((acc, item) => {
      const agentUserId = item.agentUserId;
      if (!acc[agentUserId]) {
        acc[agentUserId] = {
          ...item,
          shops: [],
        };
      }
      // 合并店铺信息
      if (item.agentShopIds?.ids && Array.isArray(item.agentShopIds.ids)) {
        acc[agentUserId].shops = item.agentShopIds.ids
          .filter(id => id !== null && id !== undefined && id !== '')
          .map(id => shopMap[id])
          .filter(Boolean);
      }

      return acc;
    }, {});

    return result;
  }

  // 查询代理商及其下属所有代理商的商铺id
  async queryAgentShopIds(agentUserId) {
    if (!agentUserId) {
      return [];
    }

    let allShopIds = new Set(); // 使用Set自动去重

    // 获取当前用户信息
    const userRes = await this.baseSysUserEntity.findOne({
      where: { id: agentUserId },
    });

    if (!userRes) {
      return [];
    }

    // 获取用户的代理级别信息
    const userLevel = await this.agentRelationEntity.findOne({
      where: { agentUserId: userRes.id },
    });

    const userLevelNum = userLevel?.level || 0;

    // 获取当前用户自己的商铺ID
    if (
      userLevel &&
      userLevel.agentShopIds &&
      Array.isArray(userLevel.agentShopIds.ids)
    ) {
      const validIds = userLevel.agentShopIds.ids.filter(
        id => id !== null && id !== undefined
      );
      validIds.forEach(id => allShopIds.add(id));
    }

    // 根据用户级别采用不同的查询逻辑
    let subAgents = [];

    // 获取最大代理层级
    const allLevels = await this.agentRelationEntity
      .createQueryBuilder('agent')
      .select('DISTINCT agent.level as level')
      .getRawMany();

    const maxLevel = Math.max(
      ...allLevels.map(item => parseInt(item.level) || 0),
      2 // 至少支持到二级代理
    );

    if (userLevelNum === 0) {
      // 超级管理员或非代理用户，查询所有代理
      for (let level = 1; level <= maxLevel; level++) {
        const agents = await this.agentRelationEntity
          .createQueryBuilder('agent')
          .where('agent.level = :level', { level })
          .getMany();
        subAgents = [...subAgents, ...agents];
      }
    } else if (userLevelNum === 1) {
      // 一级代理查询其直接下属的二级代理
      subAgents = await this.agentRelationEntity
        .createQueryBuilder('agent')
        .where(
          'agent.parentAgentId = :parentAgentId AND agent.level = :level',
          {
            parentAgentId: userRes.id,
            level: 2,
          }
        )
        .getMany();
    } else {
      // 使用递归方式查询所有下级代理
      subAgents = await this.findAllSubAgentsByLevel([userRes.id], maxLevel);
    }

    // 收集所有下属代理商的商铺ID
    for (const agent of subAgents) {
      if (agent.agentShopIds && Array.isArray(agent.agentShopIds.ids)) {
        const validIds = agent.agentShopIds.ids.filter(
          id => id !== null && id !== undefined && id !== ''
        );
        validIds.forEach(id => allShopIds.add(id));
      }
    }

    // 转换为数组并返回
    return Array.from(allShopIds);
  }

  // 查询代理商所有店铺信息
  async getAgentShopInfoAll(body) {
    if (!body.agentUserId) {
      body.agentUserId = this.ctx.admin.userId;
    }
    const agentUserId = body.agentUserId;
    const shopIds = await this.getAgentShopIdsByAgentId(agentUserId);
    if (shopIds.length === 0) {
      return [];
    }
    const shopList = await this.orderShopEntity.find({
      where: { id: In(shopIds) },
    });
    return shopList;
  }
}
